<template>
  <div>
    <el-form-item label="应用分组">
      <el-select v-if="editable"
                 v-model="applyFormData.deployGroup"
                 placeholder="请选择"
                 style="width:100%"
      >
        <el-option
            v-for="item in deployGroups"
            :key="item.name"
            :label="item.showName"
            :value="{id:item.id,name:item.name,showName:item.showName,gitBranch:item.gitBranch}"
        >
        </el-option>
      </el-select>
      <el-input v-else :value="applyFormData.deployGroup!=null?applyFormData.deployGroup.showName:''"/>
    </el-form-item>
    <el-form-item label="发布包">
      <el-select v-if="editable"
                 v-model="applyFormData.artifact"
                 placeholder="请选择"
                 style="width:100%"
                 value-key="id"
      >
        <el-option
            v-for="item in artifactList"
            :key="item.id"
            :label="item.artifactName"
            :value="{id:item.id,artifactName:item.artifactName}"
        >
        </el-option>
      </el-select>
      <el-input v-else :value="applyFormData.artifact!=null?applyFormData.artifact.artifactName:''"/>
    </el-form-item>
  </div>
</template>
<script>
import {deployGroupListApi} from "@/api/manage";
import {artifactListApi} from "@/api/build";

export default {
  props: {
    appName: String,
    editable: Boolean,
    applyFormData: {
      deployGroup: {},
      artifact: {},
    },
  },
  data() {
    return {
      artifactList: [],
      deployGroups: [],
    };
  },
  watch: {
    appName() {
      console.log("watch appName", this.applyFormData);
      if (this.editable) {
        this.$set(this.applyFormData, "deployGroup", null);
        this.$set(this.applyFormData, "artifact", null);
        this.loadGroups();
      }
    },
    applyFormData(newData, oldData) {
      console.log("watch applyFormData", newData, oldData)
      if (newData.deployGroup != null) {
        if (this.artifactList.length == 0 || oldData.deployGroup == null || oldData.deployGroup.name != newData.deployGroup.name) {
          this.loadArtifactList();
        }
      }
    }
  },
  methods: {
    async loadGroups() {
      if (this.appName) {
        this.deployGroups = await deployGroupListApi(this.appName);
      }
    },
    async loadArtifactList() {
      this.artifactList = [];
      if (this.applyFormData.deployGroup) {
        this.artifactList = await artifactListApi(this.appName, this.applyFormData.deployGroup.gitBranch);
      }
    }
  },
  created() {
    this.loadGroups();
    this.loadArtifactList();
  }

};
</script>